package org.kele.sc2020.proivder.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.kele.sc2020.proivder.service.InstanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class InstanceServiceImpl implements InstanceService {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private Environment environment;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<ServiceInstance> findAvailableInstaces() {

        List<ServiceInstance> instances = discoveryClient.getInstances(environment.getProperty("spring.application.name"));
        if (confirmInstanceHealth()) {
            return instances.parallelStream().filter(this::doComfirmInstanceHealth).collect(Collectors.toList());
        }
        return instances;
    }

    private boolean doComfirmInstanceHealth(ServiceInstance serviceInstance) {
        String url = CharSequenceUtil.format("http://{}:{}/actuator/health", serviceInstance.getHost(), serviceInstance.getPort());
        try {
            String forObject = restTemplate.getForObject(url, String.class);
            return StringUtils.equalsIgnoreCase(forObject, "{\"status\":\"UP\"}");
        } catch (Exception e) {
            log.warn("check instacne failed ... make it false");
        }
        return false;
    }
}
